package ml.kgc.dao;

import java.sql.*;

public class News2 {
    //查找特定标题的新闻信息
    public void getNewsByTitle(String title){
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url="jdbc:mysql://127.0.0.1:3306/kgcnews";
            connection = DriverManager.getConnection(url, "root", "root");
            String sql="select id,title from news_detail where title=?";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, title);
            rs = pstmt.executeQuery();
            while(rs.next()){
                int id = rs.getInt("id"); //rs.getInt(1);
                String newsTitle = rs.getString("title");

                System.out.println(id+"\t"+newsTitle);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally{
            try {
                rs.close();
                pstmt.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        News2 newsDao = new News2();
        newsDao.getNewsByTitle("Java Web开课啦");
        //newsDao.getNewsByTitle("Java Web开课啦' or '1'='1");
    }

}
